package com.xyzwps.orm.ormlite.repository;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.field.DatabaseFieldConfig;
import com.j256.ormlite.jdbc.DataSourceConnectionSource;
import com.j256.ormlite.table.DatabaseTableConfig;
import com.xyzwps.orm.model.Tag;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class TablesConfig {

    private final DataSourceConnectionSource dscs;

    public TablesConfig(DataSourceConnectionSource dscs) {
        this.dscs = Objects.requireNonNull(dscs);
    }

    public Dao<Tag, Integer> tagDao() {
        List<DatabaseFieldConfig> fieldConfigs = new ArrayList<>();

        var fTagId = new DatabaseFieldConfig("tagId");
        fTagId.setColumnName("tag_id");
        fTagId.setGeneratedId(true);
        fTagId.setCanBeNull(false);
        fieldConfigs.add(fTagId);

        var fUserId = new DatabaseFieldConfig("userId");
        fUserId.setColumnName("user_id");
        fUserId.setCanBeNull(false);
        // TODO: 如何表达联合唯一键
        fUserId.setUniqueCombo(true);
        fieldConfigs.add(fUserId);

        var fTagName = new DatabaseFieldConfig("tagName");
        fTagName.setColumnName("tag_name");
        fTagName.setCanBeNull(false);
        fTagName.setUniqueCombo(true);
        fieldConfigs.add(fTagName);

        DatabaseTableConfig<Tag> tableConfig = new DatabaseTableConfig<>(dscs.getDatabaseType(), Tag.class, fieldConfigs);
        try {
            return DaoManager.createDao(dscs, tableConfig);
        } catch (SQLException ex) {
            throw new IllegalStateException(ex);
        }
    }
}
